﻿$(function () {
    var gid = $('#gid').val(),
        shopId = $('#shopid').val(),
     partnerid = $("#partnerid").val(),
    SkuId = gid + '_0_0_0';
    var gidName = $('#gidName').val();
    var relativePath = $('#relativePath').val();
    var hskuid = $('#skuid').val();

    var OtherShops = '';
    //判断是否支持积分兑换
    if ($("#IsExchange").val() != 1) {
        $("#DuiHuan").hide();
        $("#InitCartUrl").css('margin-left', '40px');
        $("#DuiHuan a").css('background', '#C2C2C2');
        $("#DuiHuan a").attr('name', "");
        $("#DuiHuan a").attr('id', "");
        $("#DuiHuan a").attr('href', '#');
    } else {
        //判断积分不足积分兑换按钮为灰色 
        if (parseInt($("#ExchangeAmount").val()) <= parseInt($("#AllIntergral").val()) && $("#IsExchange").val() == 1 && $("#EnoughCash").val() == 1) {
            $("#DuiHuan").show();
            $("#InitCartUrl").css('margin-left', '0px');
        }
        else {
            if ($(".L-line a").html() != "请登录") {
                $("#DuiHuan").show();
                $("#InitCartUrl").css('margin-left', '0px');
                $("#DuiHuan a").css('background', '#C2C2C2');
                $("#DuiHuan a").attr('name', "");
                $("#DuiHuan a").attr('id', "");
                $("#DuiHuan a").attr('href', '#');
                $("#DuiHuan").unbind();
            } else {
                $("#DuiHuan").show();
                $("#InitCartUrl").css('margin-left', '0px');
            }
        }
    }
    //sku操作初始化
    $('#choose').himallSku({
        data: { pId: gid },
        spec: '.choose-sku',
        resultClass: {
            price: '#jd-price',
            stock: '#stockProduct'
        },
        ajaxUrl: '/Product/GetSKUInfo',
        skuPosition: 'skuArray',
        callBack: function (select) {
            SkuId = select.SkuId;
            var result = '';
            $('#choose .selected a').each(function () {
                result += '<strong>“' + this.title + '“ </strong> ';
            })
            $('#choose-result .dd').html('已选择：' + result);
        }
    });

    //$.ajax({
    //    type: "POST",
    //    url: "/Product/GetSKUInfo",
    //    data: { pId: gid },
    //    success: function (select) {
    //        SkuId = select.skuArray[0].SkuId;
    //    }
    //});

    $('#sp-hot-sale .mt span').hover(function () {
        $(this).addClass('cur').siblings().removeClass();
        $(this).parent().siblings().children().eq($(this).index()).show().siblings().hide();
    });

    $("#OrderNow").click(function () {
        bindToSettlement(SkuId);
    });
    $("#Pointsfor").click(function () {
        if ($("#DuiHuan a").attr('name') == "Pointsfor") {
            IsExchange();
            bindToSettlement(SkuId);
        }
    });
    //处理物流目的地
    var calcFreight = function () {
        var isFree = $("#hdFreightType").val();//是否包邮
        var select = $("#addressChoose").data("select");
        var isEnableCashOnDelivery = $("#isEnableCashOnDelivery").val();
        if (select != "") {
            var cityid = select.split(',')[1];//收货城市Id

            //判断是否支持货到付款
            if (select.split(',').length > 1 && isEnableCashOnDelivery == 1) {
                var addressIndex;
                if (select.split(',').length == 2) {
                    addressIndex = 1;
                }
                else {
                    addressIndex = 2;
                }
                countyid = select.split(',')[addressIndex];
                $.post("/Product/IsCashOnDelivery", { countyId: countyid, productId: gid }, function (result) {
                    if (result.success) {
                        $("#isCashOnDelivery").html("&nbsp;| &nbsp;支持货到付款");
                    }
                    else {
                        $("#isCashOnDelivery").css("display", "none");
                    }
                })
            }

            //重新计算运费
            if (parseInt(cityid) > 0 && isFree == "0") {
                var totalnum = 0;//商品总数量
                $('.wrap-input .text').each(function (i, e) {
                    if (parseInt($(e).val()) > 0) {
                        totalnum += parseInt($(e).val());
                    }
                });
                if (totalnum == 0) {
                    totalnum = 1;
                }
                //console.log(JSON.stringify({ cityId: cityid, pId: gid, count: totalnum }))
                $.ajax({
                    type: 'post',
                    url: '/Product/CalceFreight',
                    data: { cityId: cityid, pId: gid, count: totalnum },
                    dataType: "json",
                    //async: false,
                    success: function (data) {
                        if (data.success == true) {
                            $("#spFreight").html("" + data.msg + "");
                        }
                    }
                });
            }
        }
    }
    $("#buy-num").blur(function () {
        checkBuyNum();
        //if(parseInt($('#buy-num').val())>parseInt($("#stockProduct").html()))
        //{
        //    $.dialog.errorTips('不能大于库存数量');
        //    $('#buy-num').val(parseInt($("#stockProduct").html()));
        //    return false;
        //}
        calcFreight(gid);
    });

    //购买数量加减
    $('.wrap-input .btn-reduce').click(function () {
        if (parseInt($('#buy-num').val()) > 1) {
            $('#buy-num').val(parseInt($('#buy-num').val()) - 1);
        }
        //积分兑换，当兑换数量超过体系积分时，按钮变灰，不能购买
        var AllIntergral = $("#AllIntergral").val();
        var ExchangeAmount = $("#ExchangeAmount").val();
        if (AllIntergral > 0 && ExchangeAmount > 0) {
            if (parseInt($('#buy-num').val()) * ExchangeAmount > AllIntergral) {
                $("#DuiHuan a").css('background', '#dbdbdb');
                $("#DuiHuan a").attr('name', "");
                $("#DuiHuan a").attr('id', "");
            } else {
                $("#DuiHuan a").css('background', '#ff4d50');
                $("#DuiHuan a").attr('name', "Pointsfor");
                $("#DuiHuan a").attr('id', "Pointsfor");
            }
        }
        calcFreight();
    });
    $('.wrap-input .btn-add').click(function () {

        $('#buy-num').val(parseInt($('#buy-num').val()) + 1);
        //积分兑换，当兑换数量超过体系积分时，按钮变灰，不能购买
        var AllIntergral = $("#AllIntergral").val();
        var ExchangeAmount = $("#ExchangeAmount").val();
        if (AllIntergral > 0 && ExchangeAmount > 0) {
            if (parseInt($('#buy-num').val()) * ExchangeAmount > AllIntergral) {
                $("#DuiHuan a").css('background', '#dbdbdb');
                $("#DuiHuan a").attr('name', "");
                $("#DuiHuan a").attr('id', "");
            }else {
                $("#DuiHuan a").css('background', '#ff4d50');
                $("#DuiHuan a").attr('name', "Pointsfor");
                $("#DuiHuan a").attr('id', "Pointsfor");
            }
        }
        checkBuyNum();
        calcFreight();
        //alert(parseInt($('#buy-num').val())+1
    });

    $("#easyBuyBtn").click(function () {
        if (parseInt($('#buy-num').val()) > parseInt($("#stockProduct").html())) {
            $.dialog.errorTips('不能大于库存数量');
            $('#buy-num').val(parseInt($("#stockProduct").html()));
            return false;
        }
        var has = $("#has").val();
        var dis = $(this).parent("#choose-btn-append").hasClass('disabled');
        if (has != 1 || dis) return;
        var len = $('#choose li .dd .selected').length;
        if (len === $('#choose').find(".choose-sku").length) {
            if (checkBuyNum()) {
                var num = $("#buy-num").val();
                location.href = "/Order/EasyBuyToOrder?skuId=" + SkuId + "&count=" + num;
                //   alert('SKUId：'+sku+'，购买数量：'+num);
            }
        } else {
            $.dialog.errorTips('请选择商品规格');

        }
    });


    loadZUHEGOU(gid);
    loadGetEnableBuyInfo(gid);
    loadProductDESC(gid, shopId);
    //loadShopCate(gid);
    loadOtherShopsBySKU(hskuid, gid);
    loadShopInfo(gid, shopId, partnerid);

    loadHotSaleProduct(gid);
    loadHotConcernedProduct(gid);
    loadProductAttr(gid);
    //    loadGetProductDesc(gid);
    loadGetCommentsNumber(gid);
    LogProduct(gid);
    loadGroup();
    commentImgPrv();
    navChange();
    //loadBoughtProducts();     
    loadManJian(gid);


    $("#shopInSearch").click(function () {
        Search();
    });

    $('#sp-keyword,#sp-price,sp-price1').keydown(function (e) {
        if (e.keyCode == 13) {
            Search();
        }
    });

    //关注商品
    $("#choose-btn-coll").click(function () {
        checkLogin(function (func) {
            addFavoriteFun(func, gid, gidName, relativePath);
        });
    });


    //加入购物车
    $("#InitCartUrl").click(function (e) {
        var _t = $(this);
        if (_t.parent().hasClass("disabled")) {
            return;
        }
        if (parseInt($('#buy-num').val()) > parseInt($("#stockProduct").html())) {
            $.dialog.errorTips('不能大于库存数量');
            $('#buy-num').val(parseInt($("#stockProduct").html()));
            return false;
        }
        var has = $("#has").val();
        var dis = $(this).parent("#choose-btn-append").hasClass('disabled');
        if (has != 1 || dis) return;
        var len = $('#choose li .dd .selected').length;
        if (len === $('#choose').find(".choose-sku").length) {
            if (checkBuyNum()) {
                var num = $("#buy-num").val();
                var loading = showLoading();
                $.ajax({
                    type: 'POST',
                    url: "/cart/AddProductToCart?skuId=" + SkuId + "&count=" + num,
                    dataType: 'json',
                    success: function (data) {
                        loading.close();
                        if (data.success == true) {
                            var cartOffset = $("#right_cart").offset(),
                                h = $(document).scrollTop();
                            flySrc = $('#spec-list li').first().find('img')[0].src,
                            flyer = $('<img class="cart-flyer" src="' + flySrc + '"/>');
                            flyer.fly({
                                start: {
                                    left: e.pageX,
                                    top: e.pageY - h - 30
                                },
                                end: {
                                    left: cartOffset.left,
                                    top: cartOffset.top - h + 30,
                                    width: 20,
                                    height: 20
                                },
                                onEnd: function () {
                                    this.destory(); //移除dom 
                                    refreshCartProducts();
                                }
                            });
                        } else {
                            loading.close();
                            $.dialog.errorTips(data.msg);
                        }
                    },
                    error: function (e) {
                        //loading.close();
                        $.dialog.errorTips('加入购物车失败');
                    }
                });
            }
        } else {
            $.dialog.errorTips("请选择商品规格！");
        }
    });
    if ($("#addressChoose").html() != "请选择") {
        calcFreight();
    }

    $('#addressChoose').click(function () {
        $(this).himallDistrict({ items: province, closeFn: function () { calcFreight(); } });
    });

    //自营店产品详情跟普通店铺不一样显示
    changeShowView(gid);

    $.post("/product/GetShopBonus", { shopid: $('#shopid').val() }, function (data) {
        if (data != undefined && data != null && typeof data.GrantPrice != "undefined") {
            var html = '<div class="dd d02" style="padding:0;margin:0;"><em class="hl_red_bg">红包</em><em class="hl_red">满<span>' + data.GrantPrice + '元</span>送红包'
                //+ '（' + data.Count + '个' + data.RandomAmountStart + '—' + data.RandomAmountEnd + '元代金券红包）'
                + '</em></div>';
            if ($(".promotion-l").length > 0) {
                $(html).appendTo(".promotion-l");
            }
            else {
                $('#summary-promotion').append('<div class="dt l l01">促销</div>' + html);
            }
        }
    });

    //组合购
    var minCollTotal,
        maxCollTotal,
        minSaleTotal,
        maxSaleTotal;
    if ($('.p-group-list').length > 0) {
        GroupPriceChange();
    }

    $('.p-group-child input').change(function () {
        GroupPriceChange();
    });



});

$(function () {
    getFavoriteFun();
})
//function getStock(skuId) {
//    $.ajax({
//        type: 'get',
//        url: '../GetStock',
//        data: { skuId: skuId },
//        dataType: 'json',
//        cache: false,// 开启ajax缓存
//        async: false,
//        success: function (data) {
//            $("#stockProduct").text(data.Stock);
//            var stock = parseInt(data.Stock);
//            var Status = parseInt(data.Status);
//            var isshoweasybt = false;
//            if (stock > 0 && Status == 1) {
//                isshoweasybt = true;
//                $("#stockProductImage").text("有货，下单后立即发货");
//                $('#choose-btn-buy').show();
//                $("#choose-btn-append").show();
//            } else {
//                $("#stockProduct").html("0");
//                $("#stockProductImage").html("缺货");
//                $("#stockProductImage").html('<div class="dd"><strong style="color:red;">提示：无货</strong></div>');
//                $("#choose-btn-append").hide();
//                $('#choose-btn-buy').hide();
//            }
//            showEasyBuyBt(isshoweasybt);

//        },
//        error: function (e) {
//            //alert(e);
//        }
//    });

//}

//同产品其他商家
function loadOtherShopsBySKU(sku, gid) {
    $.ajax({
        type: 'POST',
        url: '/product/AjaxOtherShopsBySKU',
        dataType: 'JSON',
        data: { skuid: sku, pid: gid },
        success: function (result) {
            if (result != null) {
                var html = '<div class="sameProd_show"><h3>同款展示：</h3>';
                for (var i = 0; i < result.length; i++) {                   
                    var text = '<dl><dt><img src="' + result[i].ImgPath + '"/></dt><dd><a href="/productdetail/' + result[i].Id.toString() + '.htm"><span class="price">￥' + result[i].Price + '</span><span class="shop">' + result[i].Name + '</span></a></dd></dl>';
                    html += text;
                }
                OtherShops = html + '</div>';
               //$("#").empty().append($(html));
            }
        }
    });
}

function loadZUHEGOU(pid) {
    $.ajax({
        type: 'GET',
        url: '/product/AjaxProductColloCation',
        dataType: 'HTML',
        data: { productId: pid },
        success: function (data) {
            if (data) {
                $(".bg-g").after(data);
            }
        }
    });
}

function loadManJian(pid) {


    $.ajax({
        type: 'POST',
        url: '/Product/GetFullManJian',
        dataType: 'JSON',
        data: { pid: pid },
        success: function (data) {
            if (data != null) {
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    var d = data[i];
                    html += '<div style="margin-bottom:5px;">\
                                        <em class=' + (i == 0 ? "hl_red_bg" : "hl_not_red_bg") + '>' + (i == 0 ? "满减" : "") + '</em>\
                                        <em class="hl_red">满<span>' + d.Man + '</span>元减<span>' + d.Jian + '</span>元</em>\
                                    </div>';
                }
                $(".promotion-l").append(html);
            }

        }
    });
}

function loadProductDESC(pid, shopid) {

    $.ajax({
        type: 'POST',
        url: '/Product/GetProductDesc',
        dataType: 'JSON',
        data: { pid: pid, ShopId: shopid },
        success: function (data) {
            if (data != null) {
                var html = '';
                if (data.shopImageAds != null) {
                    html += ' <div class="guan-box">\
                                        <ul class="lp-list">';
                    for (var i = 0; i < data.shopImageAds.length; i++) {
                        var shopImageAd = data.shopImageAds[i];
                        if (shopImageAd.IsShowPrice > 0) {
                            html += '<li>\
                                                <a target="_blank" href="' + shopImageAd.Url + '">\
                                                    <div class="lp-icon">\
                                                    </div>\
                                                    <div class="lp-img">\
                                                        <img src="' + shopImageAd.ImageUrl + '">\
                                                    </div>\
                                                    <p class="lp-price">￥<span>' + shopImageAd.SalePrice + '</span></p>\
                                                    <h1 class="lp-name">' + shopImageAd.ProductName + '</h1>\
                                                </a>\
                                            </li>';
                        } else {
                            html += ' <li>\
                                                <a target="_blank" href="' + shopImageAd.Url + '">\
                                                    <img class="lazyload" src="~/Areas/Web/images/blank.gif" data-url="' + shopImageAd.ImageUrl + '">\
                                                </a>\
                                                <div shop_id="0"></div>\
                                            </li>';
                        }
                    }

                    html += '    </ul>\
                                    </div>';
                }

                if (data.ProductDescriptionTemplatesTop != null) {
                    for (var i = 0; i < data.ProductDescriptionTemplatesTop.length; i++) {
                        html += ' <div style="text-align: center">' + data.ProductDescriptionTemplatesTop[i].HtmlContent + '</div>';
                    }
                }

                if (data.pdesc != null) {
                    html += data.pdesc;
                }

                if (data.ProductDescriptionTemplatesBommon != null) {
                    for (var i = 0; i < data.ProductDescriptionTemplatesBommon.length; i++) {
                        html += ' <div style="text-align: center">' + data.ProductDescriptionTemplatesBommon[i].HtmlContent + '</div>';
                    }
                }

                $("#product-detail-1").append(html);
            }
        }

    });

}

///买了又买
function loadBoughtProducts() {

    if (true) {

        var html = '    <div class="m m2 m3">\
                                <div class="mt">\
                                    <h2>购买该商品的还购买了</h2>\
                                </div>\
                                <div class="mc">\
                                    <ul>\
                                        @foreach (var p in Model)\
                                {\
                                    <li class="fore1">\
                                        <div class="p-img">\
                                            <a href="@Url.Action("detail", "Product" , new { id=@p.Id })" title="@p.Name" target="_blank">\
                                                <img src="@Himall.Core.HimallIO.GetProductSizeImage(p.ImgPath,1,220)" alt="@p.Name">\
                                            </a>\
                                        </div>\
                                        <div class="p-name">\
                                            <a href="@Url.Action("detail", "Product" , new { id=@p.Id })" title="@p.Name" target="_blank">@p.Name</a>\
                                        </div>\
                                        <div class="p-info p-bfc">\
                                            <div class="p-price"><strong>￥@p.Price.ToString("f2")</strong></div>\
                                        </div>\
                                    </li>\
                                }\
                                </ul>\
                            </div>\
                        </div>';
        $("#sp-hot-sale ").append(html);
    }


}

function loadGroup() {
    if ($('.p-group-child li').length > 3) {
        $('.group-arrow').show();
    }

    var groupPage = 1;
    var groupI = 3; //每版放3个图片 
    var groupContent = $(".p-group-child-box");
    var groupContentList = $(".p-group-child");
    var groupHeight = groupContent.height();
    var groupLen = groupContent.find("li").length;
    var groupPageCount = Math.ceil(groupLen / groupI);
    //向后 按钮  
    $(".group-arrow-next").click(function () {
        if (!groupContentList.is(":animated")) {
            if (groupPage == groupPageCount) {
                groupContentList.animate({ top: '0px' }, 300);
                groupPage = 1;
            } else {
                groupContentList.animate({ top: '-=' + groupHeight }, 300);
                groupPage++;
            }
        }
    });
    //往前 按钮  
    $(".group-arrow-pre").click(function () {
        if (!groupContentList.is(":animated")) {
            if (groupPage == 1) {
                groupContentList.animate({ top: '-=' + groupHeight * (groupPageCount - 1) }, 300);
                groupPage = groupPageCount;
            } else {
                groupContentList.animate({ top: '+=' + groupHeight }, 300);
                groupPage--;
            }
        }

    });
}
function commentImgPrv() {
    //评论图片预览
    $(document).on("click", ".after-service-img img ", function () {
        $(this).addClass("active").siblings().removeClass("active");
        $(".preview-img img").attr("src", $(this).attr("src"));
        $(this).parent().siblings(".preview-img").show();
    });
    $("body").click(function () {
        $(".preview-img").hide();
        $('.after-service-img img.active').removeClass();
    });
}

function navChange() {
    //导航切换
    $('.tab .comment-li').click(function () {
        $('#product-detail .mc').hide();
        $(this).addClass('curr').siblings().removeClass('curr');
        $(document).scrollTop($('#comment').offset().top -52);
    });
    $('.tab .consult-li').click(function () {
        $('#product-detail .mc').hide();
        $(this).addClass('curr').siblings().removeClass('curr');
        $(document).scrollTop($('#consult').offset().top -52);
    });
    $('.tab .goods-li').click(function () {
        $('#product-detail .mc').show();
        $(this).addClass('curr').siblings().removeClass('curr');
        $(document).scrollTop($('#product-detail').offset().top);
    });

    //导航浮动
    $(window).scroll(function () {
        if ($(document).scrollTop() >= $('#product-detail').offset().top)
            $('#product-detail .mt').addClass('nav-fixed');
        else
            $('#product-detail .mt').removeClass('nav-fixed');
    });
}

//处理轻松购按钮的显示
function showEasyBuyBt(isshow, isComple) {
    var isshowbt = false;
    var iscomple = false;
    try {
        iscomple = isComple || false;
    } catch (ex) {
        iscomple = false;
    }
    isshowbt = !!isshow;
    if (isshowbt) {
        var easybuybt = $("#choose-btn-easybuy");
        easybuybt.hide();   //不启用轻松购 by DZY[150713]
        if (false) {
            var curisshow = easybuybt.is(":visible");
            if (iscomple) curisshow = true;
            if (isshowbt && curisshow) {
                easybuybt.show();
            } else {
                easybuybt.hide();
            }
        }
    }
}

function loadShopInfo(gid, shopId, partnerid) {
    /* 计算规则：
高 （店铺得分-同行业平均分）/（同行业商家最高得分-同行业平均分）
低 （同行业平均分-店铺得分）/（同行业平均分-同行业商家最高低分）
*/
    var showShop = $('#showShop').val();
    showShop = !!showShop;

    $.ajax({
        type: 'get',
        url: '/Product/GetShopInfo',
            data: { sid: shopId, productId: gid, partnerid: partnerid
    },
        dataType: 'json',
        cache: true,// 开启ajax缓存
        success: function (data) {
            if (data && data.IsSelf == true) {
                var brandLogo = data.BrandLogo;
                var html = "";
                if (brandLogo == "") {
                    html += '<dl id="seller" style="border-bottom: 1px dashed #ccc8c8;border-top: 1px solid #ccc8c8; padding-left:0; text-align:center;"><dt style="color:#fff;background-color:#ff4d50; padding:2px 10px;font-size:14px;">自营</dt><span style="font-size:16px;margin-left:40px;"><a href="/Shop/Home/' +data.Id.toString() + '">中酒自营店</a></span></dl>';
                }
                else {
                    html += '<dl id="seller" style="border-top:3px solid #ff4d50; padding-left:0; text-align:center;"><a href="/brand/' +data.BrandId + '.htm" target=_blank> <img  width="100" height="50" src="' +data.BrandLogo + '" /> </a></dl><dl style="padding:15px 0 15px 10px;border-bottom: 1px dashed #ccc8c8;border-top: 1px solid #ccc8c8;"><dt style="color:#fff;background-color:#ff4d50; padding:2px 10px;font-size:14px;">自营</dt><span style="font-size:16px;margin-left:40px;"><a href="/Shop/Home/' +data.Id.toString() + '">中酒自营店</a></span></dl>';
                }
                //html += '<dl id="hotline">' + $("#online-service").html() + '</dl>';
                html += '<dl id="hotline"></dl>';
                if (data.IsSevenDayNoReasonReturn || data.IsCustomerSecurity || data.TimelyDelivery) {
                    html += '<h3>服务支持：</h3>';
                    if (data.IsSevenDayNoReasonReturn) {
                        html += '<dl class="pop-ensure"><dt><img src="/Images/SevenDay.jpg">  七天无理由退换货</dt></dl>';
                    }
                    if (data.IsCustomerSecurity) {
                        html += '<dl class="pop-ensure"><dt><img src="/Images/Security.jpg">  消费者保障服务</dt></dl>';
                    }
                    if (data.TimelyDelivery) {
                        html += '<dl class="pop-ensure"><dt><img src="/Images/TimelyDelivery.jpg"> 及时发货</dt></dl>';
                    }
                }
                html += OtherShops;
                $("#brand-bar-pop").show().append($(html));
                $.ajax({
                    type: 'GET',
                    url: '/product/AjaxCustmerServices',
                    dataType: 'HTML',
                        data: { shopId: shopId
                },
                    success: function (data) {
                        if (data) {
                            $("#hotline").html('<dd>' + data + '</dd>');
                        }
                    }
                });


                loadBuyGift(data.Id, gid);//加载赠品
                loadFullGift(data.Id, gid);//加载满赠品

            } else {
                var shopinfo = '<div><img src="http://img6.zhongjiu.cn/resourceb2b2c/Storage/Shop/' +data.Id.toString() + '/ImageAd/logo.png"></div><dd><a target="_blank" style="color:#222;" href="/Shop/Home/' +data.Id.toString() + '">' +data.Name + '</a></dd>';
                if (showShop) {
                    shopinfo = '<dd>' +data.Name + '</dd>';
                }
                var html = '<dl id="seller">' +
					shopinfo +
					'</dl>';
                if (data.CashDeposits > 0) {
                    html += '<dl class="pop-money"><dt>资质：</dt><dd><span title="该卖家已缴纳保证金' +data.CashDeposits + '元">' +data.CashDeposits + '元</span></dd></dl>'
                }
                html += '<div id="evaluate-detail">' +
                '<div class="mc">' +
                '<dl >' +
                '<dt>描述相符：</dt>' +
                '<dd title="（商家得分-行业平均得分）/（行业商家最高得分-行业平均得分）">' +
                '<span class="' +data.productAndDescriptionColor + '">' +data.productAndDescription + '</span>' +
                '<i class="' +data.productAndDescriptionImage + '"></i>' +
                '<em class="' +data.productAndDescriptionColor + '">' +data.productAndDescriptionContrast + '</em>' +
                '</dd>' +
                '</dl>' +
                '<dl>' +
                '<dt>发货速度：</dt>' +
                '<dd title="（行业平均得分-商家得分）/（行业平均得分-行业商家最低得分）">' +
                '<span class="' +data.sellerDeliverySpeedColor + '">' +data.sellerDeliverySpeed + '</span>' +
                '<i class="' +data.sellerDeliverySpeedImage + '"></i>' +
                '<em class="' +data.sellerDeliverySpeedColor + '">' +data.sellerDeliverySpeedContrast + '</em>' +
                '</dd>' +
                '</dl>' +
                '<dl>' +
                '<dt>服务态度：</dt>' +
                '<dd title="（行业平均得分-商家得分）/（行业平均得分-行业商家最低得分）">' +
                 '<span class="' +data.sellerServiceAttitudeColor + '">' +data.sellerServiceAttitude + '</span>' +
                '<i class="' +data.sellerServiceAttitudeImage + '"></i>' +
                 '<em class="' +data.sellerServiceAttitudeColor + '">' +data.sellerServiceAttitudeContrast + '</em>' +
                '</dd>' +
                '</dl>' +
                '</div>' +
                '</div>' +
                '<dl id="online-service"><div class="line"></div>' +
                '</dl>' +
                //'<dl id="pop-company">' + $("#online-service").html() + '</dl>';
                '<dl id="pop-company"></dl>';
                if (data.IsSevenDayNoReasonReturn || data.IsCustomerSecurity || data.TimelyDelivery) {
                    html += '<h3>服务支持：</h3>';
                    if (data.IsSevenDayNoReasonReturn) {
                        html += '<dl class="pop-ensure"><dt><a href="/Article/Category"><img src="/Images/SevenDay.jpg">  七天无理由退换货</a></dt></dl>';
                    }
                    if (data.IsCustomerSecurity) {
                        html += '<dl class="pop-ensure"><dt><a href="/Article/Category"><img src="/Images/Security.jpg">  消费者保障服务</a></dt></dl>';
                    }
                    if (data.TimelyDelivery) {
                        html += '<dl class="pop-ensure"><dt><a href="/Article/Category"><img src="/Images/TimelyDelivery.jpg"> 及时发货</a></dt></dl>';
                    }
                }
                html += '<div id="enter-shop">' +
                '<a target="_blank" href="/Shop/Home/' +data.Id + '">进入店铺</a>' +
                '<a href="javascript:addFavorite(' +data.Id + ')">收藏店铺</a>' +
                '</div>';
                html += OtherShops;
                $("#brand-bar-pop").show().append($(html));

                $.ajax({
                    type: 'GET',
                    url: '/product/AjaxCustmerServices',
                    dataType: 'HTML',
                        data: { shopId: shopId
                },
                    success: function (data) {
                        if (data) {
                            $("#pop-company").html('<dd>' + data + '</dd>');
                        }
                    }
                });


                //if ($('#online-service').html() == '<div class="line"></div>') { $('#online-service').hide() }
                if (showShop) { $("#enter-shop").hide();
            }

                loadBuyGift(data.Id, gid);//加载赠品
                loadFullGift(data.Id, gid);//加载满赠品
            }

            //商品评价
            $('.summary-grade span').addClass("sa" +data.ProductMark);

            //加载限购信息
            if (data.LimitBuyCount > 0) {
                var html = '<div style="margin-bottom:5px;"><em class="hl_red_bg">限购</em><em class="hl_red">限购<span>' +data.LimitBuyCount + '</span>件</em></div>';
                $(".promotion-l").append(html);
            }

        },
        error: function (e) {
            //alert(e);
        }
    });
    return;

}

function loadShopCate(gid) {

    $.ajax({
        type: 'get',
        url: '/Product/GetShopCate',
            data: { gid: gid
    },
        dataType: 'json',
        cache: true,// 开启ajax缓存
        success: function (data) {
            if (data) {
                //console.log(data);
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    var text = '<dl><dt><a href="/Shop/SearchAd?cid=' +data[i].Id + '&sid=' +$('#shopid').val() + '&pageNo=1" target="_blank"><s></s>' +data[i].Name + '</a></dt>';
                    if (data[i].SubCategory.length > 0) {
                        for (var j = 0; j < data[i].SubCategory.length; j++) {
                            text += '<dd><a href="/Shop/SearchAd?cid=' +data[i].SubCategory[j].Id + '&sid=' +$('#shopid').val() + '&pageNo=1" target="_blank">' +data[i].SubCategory[j].Name + '</a></dd>';
                        }
                    }
                    text += '</dl>';
                    html += text;
                }
                $("#shopCateDiv").empty().append($(html));
            }
        },
        error: function (e) {
            //alert(e);
        }
    });
}

function loadHotSaleProduct() {
    $.ajax({
        type: 'get',
        url: '/Product/GetHotSaleProduct',
            data: { sid: $("#shopid").val()
    },
        dataType: 'json',
        cache: true,// 开启ajax缓存
        success: function (data) {
            if (data) {
                //console.log(data);
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    var text = '<li class="fore1">' +
                    '<div class="p-img"><a href="/productdetail/' +data[i].Id.toString() + '.htm" target="_blank"><img alt="' +data[i].Name + '" src="' +data[i].ImgPath + '" /></a></div>' +
                            '<div class="p-name"><a href="/productdetail/' +data[i].Id.toString() + '.htm" target="_blank" title="">' +data[i].Name + '</a></div>' +
                            '<div class="p-info p-bfc">' +
                                '<div class="p-count fl"><s>' + (i +1).toString() + '</s><b>热销' +data[i].SaleCount.toString() + '件</b></div>' +
                                '<div class="p-price fr"><strong>￥+' +data[i].Price.toString + '</strong></div>' +
                            '</div>' +
                        '</li>';
                    html += text;
                }
                $("#hotsaleDiv").empty().append($(html));
            }
        },
        error: function (e) {
            //alert(e);
        }
    });
}


function LogProduct(gid) {
    $.ajax({
        type: 'post',
        url: '/Product/LogProduct',
            data: { pid: gid
    },
        dataType: 'json',
        cache: false,// 开启ajax缓存
        success: function (data) {
            if (data) {
                //console.log(data);
            }
        },
        error: function (e) {
            //alert(e);
        }
    });
}

function loadHotConcernedProduct() {
    $.ajax({
        type: 'get',
        url: '/Product/GetHotConcernedProduct',
            data: { sid: $("#shopid").val()
    },
        dataType: 'json',
        cache: true,// 开启ajax缓存
        success: function (data) {
            if (data) {
                //console.log(data);
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    var text = '<li class="fore1">' +
                    '<div class="p-img"><a href="/productdetail/' +data[i].Id.toString() + '.htm" target="_blank"><img alt="' +data[i].Name + '" src="' +data[i].ImgPath + '" /></a></div>' +
                            '<div class="p-name"><a href="/productdetail/' +data[i].Id.toString() + '.htm" target="_blank" title="">' +data[i].Name + '</a></div>' +
                            '<div class="p-info p-bfc">' +
                                '<div class="p-count fl"><s>' + (i +1).toString() + '</s><b>关注' +data[i].SaleCount.toString() + '次</b></div>' +
                                '<div class="p-price fr"><strong>￥+' +data[i].Price.toString + '</strong></div>' +
                            '</div>' +
                        '</li>';
                    html += text;
                }
                $("#hotConcerned").empty().append($(html));
            }
        },
        error: function (e) {
            //alert(e);
        }
    });
}


function loadGetProductDesc(gid) {
    $.ajax({
        type: 'get',
        url: '/Product/GetProductDesc',
            data: { pid: gid
    },
        dataType: 'json',
        cache: true,// 开启ajax缓存
        success: function (data) {
            if (data) {
                //console.log(data);
                if (data.DescriptionPrefix.length > 0) {
                    $("#product-html").append($(data.DescriptionPrefix));
                }
                if (data.ProductDescription.length > 0) {
                    var prodes = $(data.ProductDescription);
                    var imgs = $("img", prodes);
                    imgs.each(function () {
                        var _t = $(this);
                        _t.attr("data-url", _t.attr("src"));  //图片延时加载
                        _t.addClass("lazyload");
                        _t.attr("src", "/Areas/Web/images/blank.gif");  //图片延时加载
                    });
                    $("#product-html").append(prodes);

                    //图片延迟加载
                    $(".lazyload").scrollLoading();
                }
                if (data.DescriptiondSuffix.length > 0) {
                    $("#product-html").append($(data.DescriptiondSuffix));
                }
            }
        },
        error: function (e) {
            //alert(e);
        }
    });
}

function loadGetEnableBuyInfo(gid) {
    //if ($('#IsExpiredShop').val()) {
    //    $('#summary-price').html('<div class="dd"><strong style="font-size:25px;color:red;">提示：该商品所在店铺已过期！</strong></div>');
    //    $('#choose-btn-buy').hide();
    //    $("#choose-btn-append").addClass("disabled");
    //} else {
    $.ajax({
        type: 'get',
        url: '/Product/GetEnableBuyInfo',
            data: { gid: gid
    },
        dataType: 'json',
        cache: true,// 开启ajax缓存
        //async: false,//同步
        success: function (data) {
            if (data) {
                if (data.IsExpiredShop) {
                    $('#summary-price').html('<div class="dd"><strong style="font-size:25px;color:red;">提示：该商品所在店铺已过期！</strong></div>');
                    $('#choose-btn-buy').hide();
                    $("#choose-btn-append").addClass("disabled");
                } else if (data.IsPreheat && !IsNormalPurchase) {
                    var html = '<div id="choose-btn-active" class="btn active-now">\
                                        <a href="/LimitTimeBuy/Detail/' +data.FlashSaleId + '">去参加活动</a>\
                                    </div>';
                    $("#choose-btns").html(html);
                    html = ' <a href="/LimitTimeBuy/Detail/' +data.FlashSaleId + '">\
                                    <div id="limited-tag">\
                                        <span>限时购</span><span>此商品参加限时购活动，还有<i>' +data.TotalHours + '时' +data.Minutes + '分</i>开始</span>\
                                    </div>\
                                </a>';
                    $("#limitbuyyure").html();
                }
                else if (!data.hasSKU) {
                    $("#stockProductImage").html("缺货");
                    $("#stockProduct").html("0");

                    $("#OrderNow").css({ "cursor": "default", "background-color": "#C2C2C2"
                });
                    $("#OrderNow").attr('href', '#');
                    $("#OrderNow").unbind();
                    $("#InitCartUrl").css({ "cursor": "default", "border": "2px solid #D4D4D4", "color": "white", "background-color": "#C2C2C2"
                });
                    $("#InitCartUrl").attr('href', '#');
                    $("#InitCartUrl").unbind();
                    //积分兑换置灰
                    $("#DuiHuan a").css('background', '#C2C2C2');
                    $("#DuiHuan a").attr('name', "");
                    $("#DuiHuan a").attr('id', "");
                    $("#DuiHuan a").attr('href', '#');
                    $("#DuiHuan").unbind();
                }
                else if (data.IsOnSale === false) {
                    $('#summary-price').html('<div class="dd"><strong style="font-size:25px;color:red;">提示：该商品已经下架！</strong></div>');
                    $("#stockProductImage").html('<div class="dd"><strong style="color:red;">提示：无货</strong></div>');
                    $("#choose-btns").hide();
                }
                else {
                    $("#choose-btn-append").removeClass("disabled");
                    $('#choose-btn-buy').show();
                    $("#choose-btns").show();
                }
                if (data.IsOnSale && data.Logined == 1 && data.hasQuick === 1 && data.hasSKU) {
                    showEasyBuyBt(true, true);
                }

            }

        },
        error: function (e) {
            //alert(e);
        }
    });
    //   }


}

function loadGetCommentsNumber(gid) {
    $.ajax({
        type: 'get',
        url: '/Product/GetCommentsNumber',
            data: { gid: gid
    },
        dataType: 'json',
        cache: true,// 开启ajax缓存
        success: function (data) {
            if (data) {
                $("#Comments").html(data.Comments.toString());
                $("#CommentsU").html("(" +data.Comments.toString() + ")");
                $("#ConsU").html("(" +data.Consultations.toString() + ")");
            }
        },
        error: function (e) {
            //alert(e);
        }
    });
}
function loadProductAttr(gid) {
    var brand = $("#showpp").val();
    $.ajax({
        type: 'get',
        url: '/Product/GetProductAttr',
            data: { pid: gid
    },
        dataType: 'json',
        cache: true,// 开启ajax缓存
        success: function (data) {
            if (data) {
                //console.log(data);
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    var values = "";
                    if (brand != "") {
                        if (data[i].Name != "品牌") {
                            for (var j = 0; j < data[i].AttrValues.length; j++) {
                                values += data[i].AttrValues[j].Name + ",";
                            }
                            values = values.substr(0, values.length -1)


                            var text = '<li>' +data[i].Name + '：' + values + '</li>';

                            html += text;
                        }
                    }
                    if (brand == "") {
                        for (var j = 0; j < data[i].AttrValues.length; j++) {
                            values += data[i].AttrValues[j].Name + ",";
                        }
                        values = values.substr(0, values.length -1)

                        var text = '<li>' +data[i].Name + '：' + values + '</li>';
                        html += text;
                    }
                }
                //console.log(data);
                $("#detail-list").append($(html));
            }
        },
        error: function (e) {
            //alert(e);
        }
    });
}

//if (brand != null) {
//    for (var j = 0; j < data[i].AttrValues.length; j++) {
//        values += data[i].AttrValues[j].Name + ",";
//    }
//    values = values.substr(0, values.length - 1)
//    if (data[i].Name != "品牌") {
//        var text = '<li>' + data[i].Name + '：' + values + '</li>';
//    }
//    html += text;
//} else {
//    for (var j = 0; j < data[i].AttrValues.length; j++) {
//        values += data[i].AttrValues[j].Name + ",";
//    }
//    values = values.substr(0, values.length - 1)
//    var text = '<li>' + data[i].Name + '：' + values + '</li>';
//    html += text;

//}
function Search() {
    var start = isNaN(parseFloat($("#sp-price").val())) ? 0 : parseFloat($("#sp-price").val());
    var end = isNaN(parseFloat($("#sp-price1").val())) ? 0 : parseFloat($("#sp-price1").val());
    var shopid = $("#shopid").val();

    var keyword = $("#sp-keyword").val();
    if (keyword.length === 0 && start == end) {
        $.dialog.errorTips('请输入关键字或者价格区间');
        return;
    }
    location.href = "/Shop/SearchAd?pageNo=1&sid=" + shopid + "&keywords=" + keyword + "&startPrice=" + start + "&endPrice=" +end;
}

function addFavoriteFun(callBack, gid, gidName, relativePath) {
    $.post('/Product/AddFavoriteProduct', { pid: gid
    }, function (result) {
        getFavoriteFun();
        if (result.successful == true) {
            if (result.favorited == true) {
                $.dialog.tips(result.mess);
            } else {
                var obj = $('.side-goods-list');
                //console.log(obj)
                obj.append('<li> <a href="/Product/Detail/' + gid + '" target="_blank"><img src="' + relativePath + '"></a> <p><a href="/Product/Detail/570" target="_blank">' + gidName + '</a></p></li>');
                $.dialog.succeedTips(result.mess);
            }
            (function () { callBack && callBack(); }) ();
        }

    });
}


function getFavoriteFun() {
    $.post('/Product/GetFavoriteProduct', { pid: $("#gid").val()
    }, function (result) {
        if (result.success)
            $("#choose-btn-coll").attr("class", "attent-goods");
        else
            $("#choose-btn-coll").attr("class", "attent-good");
    });
}


function getFavorite() {
    $.post('/Product/getFavorite', { shopId: shopId
    }, function (result) {
        if (result.success)
            $("#choose-btn-coll").css("attent-goods");
        else
            $("#choose-btn-coll").css("attent-good");
    });
}

function checkLogin(callBack) {
    var memberId = $.cookie('Himall-User');
    if (memberId) {
        callBack();
    }
    else {
        $.fn.login({
        }, function () {
            callBack(function () { location.reload();
        });
        }, '', '', '/Login/Login');
    }
}

function changeShowView(gid) {
    var isSellerAdminProdcut = $('#IsSellerAdminProdcut').val();
    if (isSellerAdminProdcut.toLowerCase() == "true") {
        $("#sp-search,#sp-category").show();
        $("#shopname").attr("href", "#")
        bindOfficialView(gid);
    }
    else {
        $("#sp-brand-official,#sp-category-official").hide();
    }
}

function checkBuyNum() {
    var num = 0;
    var result = true;
    try {
        num = parseInt($("#buy-num").val());
    } catch (ex) {
        num = 0;
    }
    if (num < 1) {
        $.dialog.errorTips('购买数量有误');
        $('#buy-num').val(1);
        result = false;
    }
    var stockNum = parseInt($("#stockProduct").html());
    if (num > stockNum) {
        $('#buy-num').val(stockNum);
        $.dialog.errorTips('库存仅余 ' + stockNum + '件');
    }
    return result;
}

function bindOfficialView(gid) {
    loadShopCateOfficial(gid);
    loadBrandOfficial(gid);
}

function loadBrandOfficial(gid) {

    $.ajax({
        type: 'get',
        url: '/Product/GetBrandOfficial',
            data: { gid: gid
    },
        dataType: 'json',
        cache: true,// 开启ajax缓存
        success: function (data) {
            if (data) {
                $("#brandDivOfficial").empty();
                //console.log(data);
                var html = '';
                var dataLength = data.length;
                for (var i = 0; i < data.length; i++) {
                    html += '<dd style="width:33%;float:left;text-align:center;"><a href="/Search/?b_id=' +data[i].Id + '" target="_blank"><s></s>' +data[i].Name + '</a></dd>';
                }

                $("#brandDivOfficial").append($(html));
            }
        },
        error: function (e) {
            //alert(e);
        }
    });
}

function loadShopCateOfficial(gid) {

    $.ajax({
        type: 'get',
        url: '/Product/GetShopCateOfficial',
            data: { gid: gid
    },
        dataType: 'json',
        cache: true,// 开启ajax缓存
        success: function (data) {
            if (data) {
                $("#shopCateDivOfficial").empty();
                //console.log(data);
                var html = '';
                var dataLength = data.length;
                for (var i = 0; i < data.length; i++) {
                    html += '<dd style="width:50%;float:left;text-align:center;"><a href="/Search/?cid=' +data[i].Id + '" target="_blank"><s></s>' +data[i].Name + '</a></dd>';
                }

                $("#shopCateDivOfficial").append($(html));
            }
        },
        error: function (e) {
            //alert(e);
        }
    });
}
var IsExchanges = false;
    function IsExchange() {//积分兑换标识
    IsExchanges = true;
}
    function bindToSettlement(SkuId) {

    if (parseInt($('#buy-num').val()) > parseInt($("#stockProduct").html())) {
        $.dialog.errorTips('不能大于库存数量');
        $('#buy-num').val(parseInt($("#stockProduct").html()));
        return false;
    }
    var has = $("#has").val();
    var dis = $(this).parent("#choose-btn-append").hasClass('disabled');
    if (has != 1 || dis) {
        return;
    }
    var len = $('#choose li .dd .selected').length;
    if (len === $('#choose').find(".choose-sku").length) {
        var memberId = $.cookie('Himall-User');
        var num = $("#buy-num").val();
        if (memberId) {
            if (checkBuyNum()) {
                    var url = "/Order/SubmitByProductId?skuIds=" + SkuId + "&counts=" + num + "&IsExchange=" + IsExchanges;
                    location.href = url;
            }
        }
        else {
            $.fn.login({
            }, function () {
                if (parseInt($("#ExchangeAmount").val()) <= parseInt($("#AllIntergral").val()) && $("#IsExchange").val() == 1 && $("#EnoughCash").val() == 1) {
                    location.href = "/Order/SubmitByProductId?skuIds=" + SkuId + "&counts=" + num + "&IsExchange=" + IsExchanges;
                } else {
                    $("#DuiHuan").show();
                    $("#InitCartUrl").css('margin-left', '0px');
                    $("#DuiHuan a").css('background', '#C2C2C2');
                    $("#DuiHuan a").attr('name', "");
                    $("#DuiHuan a").attr('id', "");
                    $("#DuiHuan a").attr('href', '#');
                    $("#DuiHuan").unbind();
                    //window.location.href;
                    window.location.reload();
                }
            }, '', '', '/Login/Login');
        }
    }
    else {
        $.dialog.errorTips("请选择商品规格！");
    }



}

function addFavorite(shopId) {
    checkLogin(function (callBack) {
        var loading = showLoading();
        $.post('/Product/AddFavorite', { shopId: shopId
        }, function (result) {
            loading.close();
            if (result.success)
                $.dialog.succeedTips('收藏店铺成功', function () { callBack && callBack();
            });
            else
                $.dialog.tips(result.msg, function () { callBack && callBack();
        });

        });
    });
}

function checkLogin(callBack) {
    var memberId = $.cookie('Himall-User');
    if (memberId) {
        callBack();
    }
    else {
        $.fn.login({
        }, function () {
            callBack(function () { location.reload();
        });
        }, './', '', '/Login/Login');
    }
}

function GroupPriceChange() {
    var mCheck = $('.p-group-main input:checked')
    minCollTotal = mCheck.data('mincollprice');
    maxCollTotal = mCheck.data('maxcollprice');
    minSaleTotal = mCheck.data('minsaleprice');
    maxSaleTotal = mCheck.data('maxsaleprice');

    $('.p-group-child input:checked').each(function () {
        minCollTotal += $(this).data('mincollprice');
        maxCollTotal += $(this).data('maxcollprice');
        minSaleTotal += $(this).data('minsaleprice');
        maxSaleTotal += $(this).data('maxsaleprice');
    });
    if (minCollTotal != maxCollTotal)
        $('#collTotalPrice').text('¥' +minCollTotal.toFixed(2) + '-' +maxCollTotal.toFixed(2));
    else
        $('#collTotalPrice').text('¥' +minCollTotal.toFixed(2));
    if (minSaleTotal != maxSaleTotal)
        $('#saleTotalPrice').text(minSaleTotal.toFixed(2) + '-' +maxSaleTotal.toFixed(2));
    else
        $('#saleTotalPrice').text(minSaleTotal.toFixed(2));
    if (minSaleTotal - minCollTotal != maxSaleTotal -maxCollTotal)
        $('#groupPriceMinus').text('¥' + (minSaleTotal -minCollTotal).toFixed(2) + '-' + (maxSaleTotal -maxCollTotal).toFixed(2))
    else
        $('#groupPriceMinus').text('¥' + (minSaleTotal -minCollTotal).toFixed(0))
}


function CollocationBuy() {
    var chk = $(".collochk:checked");
    var pids = "";
    var colloPids = "";
    if (chk.length < 2) {
        $.dialog.errorTips("请至少选择一个商品组合购买！");
        return;
    }
    else {
        chk.each(function (index, item) {
            if (index < chk.length -1) {
                pids += $(item).val() + ",";
                colloPids += $(item).data("collpid") + ",";
            }
            else {
                pids += $(item).val();
                colloPids += $(item).data("collpid");
            }
        });
    }
    $.ajax({
        url: "/Product/GetCollocationProducts",
            data: { productIds: pids, colloPids: colloPids
    },
        //async: false,
        success: function (data) {
            $("#addCollocation").html(data);
        }
    });
    $.dialog({
        title: '组合购选择',
        width: 908,
        padding: 0,
        id: 'Collocation',
        content: document.getElementById("addCollocation"),
        lock: true,
        okVal: '确定购买套餐',
        init: function () {
            var groupPrice = 0;
            for (var i = 0; i < $('.group-item').length; i++) {
                groupPrice += parseFloat($('.product-price').eq(i).text());
            }
            $('.group-price span').data('groupprice', groupPrice).text(groupPrice.toFixed(2));

            var len = $('.group-item').length;
            for (var i = 0; i < len; i++) {
                $('.SKUgroup' +i).himallSku({
                    data: {
                        pId: $('.product-item').eq(i).data('productid'),
                        colloPid: $('.product-item').eq(i).data('colloproductid')
                    },
                    spec: '.choose-sku',
                    resultClass: {
                        price: '.product-price',
                        stock: '.group-stock'
                    },
                    ajaxUrl: '/Product/GetSKUInfo',
                    skuPosition: 'skuArray',
                    callBack: function (select, _this) {
                        $('.group-skuId', _this).val(select.SkuId);
                        var groupPrice = 0;
                        for (var i = 0; i < $('.group-item').length; i++) {
                            groupPrice += parseFloat($('.product-price').eq(i).text());
                        }
                        $('.group-price span').data('groupprice', groupPrice).text(($('#groupCounts').val() * groupPrice).toFixed(2));
                    }
                });
            }

            $('#groupCounts').keyup(function () {
                var groupPrice = $('.group-price span').data('groupprice');
                this.value = this.value.replace(/[^0-9]+/, '');
                if (this.value == '' || this.value < 1) {
                    this.value = '1';
                }
                $('.group-price span').text((this.value * groupPrice).toFixed(2));
            });

        },
        ok: function () {
            //创建订单页面
            var flag = 1,
				groupSkuids = '',
				collpids = '',
				groupcounts = '';
            $('.group-item').each(function () {
                $(this).removeClass('error');
                if ($(this).find('.selected').length != $(this).find(".choose-sku").length) {
                    $(this).addClass('error');
                    flag = 2;
                }
                if (parseInt($(this).find('.group-stock').text()) < parseInt($('#groupCounts').val())) {
                    $(this).addClass('error');
                    flag = 3;
                }
                groupSkuids += $(this).find('.group-skuId').val() + ',';
                collpids += $(this).find('.product-item').data('colloproductid') + ',';
                groupcounts += $('#groupCounts').val() + ',';


            });
            if (flag == 2) {
                $.dialog.errorTips("有未选择规格的商品");
                return false;
            }
            if (flag == 3) {
                $.dialog.errorTips("购买数大于商品库存");
                return false;
            }

            groupSkuids = groupSkuids.substring(0, groupSkuids.length -1);
            collpids = collpids.substring(0, collpids.length -1);
            groupcounts = groupcounts.substring(0, groupcounts.length -1);


            $('#skuids').val(groupSkuids);
            $('#counts').val(groupcounts);
            $('#collpids').val(collpids);
            checkLogin(function () {
                $('#CollProducts').submit();
            })

        }
    });
}
function showQrCode() {
    $.dialog({
        title: '二维码',
        lock: true,
        id: 'weixinQrCode',
        content: $("#weixinQrCode").html(),
        padding: '10px',
        init: function () {
        }
    });
};

//加载赠品
function loadBuyGift(shopId, gid) {
    $.post('/Product/GetShopBuyGift', { shopid: shopId, productidandnums: gid + "|1"
    }, function (result) {
        if (result != null) {
            var gift = document.getElementById('buygift');
            var html = '';
            for (var j = 0; j < result.length; j++) {
                var productid = result[j].ProductId;
                var productname = result[j].ProductName;
                var number = result[j].Number;
                if (j == 0) {
                    html = '<div style="margin-bottom:5px;"><em class="hl_red_bg">买赠</em><em class="hl_red"><a href="/productdetail/' + productid + '.htm" target="_blank" style="color:#2d2d2d;height:18px;width:300px;overflow: hidden;display:inline-block;white-space:nowrap;text-overflow:ellipsis;vertical-align: middle;">' + productname + '</a> x ' + number + '</em></div>';
                }
                else {
                    html += '<div style="margin-bottom:5px;"><em style=" width:40px;line-height:20px; margin-right: 25px; display: inline-block;"></em><em class="hl_red"><a href="/productdetail/' + productid + '.htm" target="_blank" style="color:#2d2d2d;height:18px;width:300px;overflow: hidden;display:inline-block;white-space:nowrap;text-overflow:ellipsis;vertical-align: middle;">' + productname + '</a> x ' + number + '</em></div>';
                }
            }
            gift.innerHTML = html;
        }
    });
}

function loadFullGift(shopId, gid) {
    $.post('/Product/GetShopFullGift', { shopid: shopId, productid: parseFloat(gid)
    }, function (result) {
        if (result != null) {
            var gift = document.getElementById('fullgift');
            var html = '';
            for (var j = 0; j < result.length; j++) {
                var amountNum = result[j].AmountNum;
                var productid = result[j].ProductId;
                var productname = result[j].ProductName;
                var number = result[j].Number;

                for (var k = 0; k < amountNum.length; k++) {
                    if (j == 0 && k == 0) {
                        html = '<div style="margin-bottom:5px;"><em class="hl_red_bg">满赠</em><em class="hl_red">满<a style="color:#2d2d2d;height:18px;width:300px;overflow: hidden;display:inline-block;white-space:nowrap;text-overflow:ellipsis;vertical-align: middle;">' +amountNum[k].ProductAmount + ' 元送 ' + productname + '</a>' +amountNum[k].GiftNum + '瓶</em></div>';

                    }
                    else {
                        html += '<div style="margin-bottom:5px;"><em style=" width:40px;line-height:20px; margin-right: 25px; display: inline-block;"></em><em class="hl_red">满<a style="color:#2d2d2d;height:18px;width:300px;overflow: hidden;display:inline-block;white-space:nowrap;text-overflow:ellipsis;vertical-align: middle;">' +amountNum[k].ProductAmount + ' 元送 ' + productname + '</a>' +amountNum[k].GiftNum + '瓶</em></div>';

                    }
                }

            }
            gift.innerHTML = html;
        }
    });
}